//
//  WZSuggestController.m
//  ETong
//
//  Created by wanzhao on 15/10/30.
//  Copyright (c) 2015年 wanzhao. All rights reserved.
//

#import "WZSuggestController.h"
#import "WZSuggestView.h"
#import "CFolderMgr.h"
#import "WZSuggestionCategory.h"
#import "WZTabBarButton.h"
#import "CContactMgr.h"
#import "CContactModel.h"

#import "MBProgressHUD+WZ.h"
#import "UIBarButtonItem+category.h"
#import "NetWorkShare.h"

@interface WZSuggestController ()

@property (nonatomic, weak) WZSuggestView *sugView;
@property (nonatomic, strong) NSMutableArray *categoryArray;
@property (nonatomic, strong) WZTabBarButton *selectedBtn;

@end

@implementation WZSuggestController

- (void)dealloc
{
    NSLog(@"WZSuggestController dealloc");
}

- (NSMutableArray *)categoryArray
{
    if (_categoryArray == nil) {
        _categoryArray = [NSMutableArray array];
    }
    return _categoryArray;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = RGBCOLORWITH16COLOR(0xeeeeee);
   
    self.navigationItem.title = @"意见反馈";
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem BarButtonItemWithImageName:nil title:@"提交" target:self sel:@selector(submitSuggestion) titleFont:Font15 titleColor:RGBCOLORWITH16COLOR(0xffffff)];
    
    WZSuggestView *sugView = [[WZSuggestView alloc] init];
    sugView.frame = CGRectMake(OppositeWidthRate(10), OppositeHeightRate(10), self.view.width - OppositeWidthRate(20), OppositeHeightRate(200));
    sugView.backgroundColor = ClearColor;
    sugView.backgroundImage = [UIImage strechingWithImageName:@"feedback_submit_box_bg"];
    sugView.placeHolder = @"请提出您宝贵的意见（大于5个字）";
    sugView.font = Font15;
    sugView.placeColor = RGBCOLORWITH16COLOR(0x999999);
    [self.view addSubview:sugView];
    self.sugView = sugView;
    
    
    [self loadSuggestionCategory];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
}

//获取意见反馈可选模块
- (void)loadSuggestionCategory
{
    [MBProgressHUD showMessage:@"加载中..." toView:self.view];
    [NetWorkShare getSuggestCategoryWithSuccessHandle:^(AFHTTPRequestOperation *operation, id responseObject) {
        [MBProgressHUD hideHUDForView:self.view];
        if (responseObject) {
            
            if ([[responseObject objectForKey:@"success"] boolValue]) {
                [self.categoryArray removeAllObjects];
                NSArray *array = [WZSuggestionCategory objectArrayWithKeyValuesArray:responseObject[@"list"]];
                if (array.count > 0) {
                    [self.categoryArray addObjectsFromArray:array];
                }
                [self setUpCategory];
            } else {
                [MBProgressHUD showError:[responseObject objectForKey:@"message"]];
            }
            
        } else {
            [MBProgressHUD showError:@"未知错误"];
        }

    } failureHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
        [MBProgressHUD hideHUDForView:self.view];
        [MBProgressHUD showError:@"网络错误"];
    }];
}

- (void)setUpCategory
{
    if (self.categoryArray.count > 0) {
        UIView *line1 = [[UIView alloc] init];
        line1.backgroundColor = RGBCOLORWITH16COLOR(0xffffff);
        line1.frame = CGRectMake(0, CGRectGetMaxY(self.sugView.frame) + 39.5f, self.view.width, 0.5f);
        [self.view addSubview:line1];
        
        UIView *line2 = [[UIView alloc] init];
        line2.backgroundColor = RGBCOLORWITH16COLOR(0xd4d4d4);
        line2.frame = CGRectMake(0, CGRectGetMaxY(line1.frame), self.view.width, 0.5f);
        [self.view addSubview:line2];
        
        UILabel *label = [[UILabel alloc] init];
        label.frame = CGRectMake(OppositeWidthRate(15), CGRectGetMaxY(line2.frame), self.view.width - OppositeWidthRate(30), OppositeHeightRate(30));
        label.text = @"问题位置";
        label.textColor = RGBCOLORWITH16COLOR(0x999999);
        label.textAlignment = UITextAlignmentLeft;
        label.font = Font12;
        [self.view addSubview:label];
        
        
        CGFloat gapW = OppositeWidthRate(15);
        CGFloat gapH = OppositeHeightRate(10);
        CGFloat x = 0;
        CGFloat y = 0;
        CGFloat w = (self.view.width - 4 * gapW) / 3.0;
        CGFloat h = OppositeHeightRate(40);
        
        for (int i = 0; i < self.categoryArray.count; i ++) {
            x = (i % 3) * (w + gapW) + gapW;
            y =  CGRectGetMaxY(label.frame) + (i / 3) * (h + gapH);
            WZSuggestionCategory *category = self.categoryArray[i];
            WZTabBarButton *btn = [self addButtonWithTitle:category.name];
            btn.category = category;
            btn.frame = CGRectMake(x, y, w, h);
        }

    }
}


- (WZTabBarButton *)addButtonWithTitle:(NSString *)title
{
    WZTabBarButton *btn = [WZTabBarButton buttonWithType:UIButtonTypeCustom];
    [btn setTitle:title forState:UIControlStateNormal];
    btn.titleLabel.font = Font15;
    [btn setTitleColor:RGBCOLORWITH16COLOR(0x333333) forState:UIControlStateNormal];
    [btn setTitleColor:RGBCOLORWITH16COLOR(0x333333) forState:UIControlStateSelected];
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setTitle:title forState:UIControlStateSelected];
    [btn setBackgroundImage:[UIImage imageNamed:@"suggestionCategoryNormal"] forState:UIControlStateNormal];
    [btn setBackgroundImage:[UIImage imageNamed:@"suggestionCategorySelected"] forState:UIControlStateSelected];
    [btn addTarget:self action:@selector(btnDidClick:) forControlEvents:UIControlEventTouchUpInside];
    btn.showsTouchWhenHighlighted = YES;
    btn.adjustsImageWhenHighlighted = NO;
    [self.view addSubview:btn];
    return btn;
}

- (void)btnDidClick:(WZTabBarButton *)btn
{
    self.selectedBtn.selected = NO;
    btn.selected = YES;
    self.selectedBtn = btn;
}
#pragma mark 提交建议
- (void)submitSuggestion
{
    
    if (![self checkIsValidSuggestion]) {
        return;
    }
    
    if (self.selectedBtn == nil) {
        [MBProgressHUD showError:@"请选择意见反馈模块"];
        return;
    }
    CAccountModel *acc = [[CFolderMgr shareInstance].accMgr getRecentlyLoginAccount];
    CContactModel *cur = [[[CContactMgr alloc] init] loadContactWithUserCode:acc.userName];
    
    [MBProgressHUD showMessage:nil toView:self.view];
    [NetWorkShare submitSuggestionWithUserId:cur.UserID suggestion:self.sugView.text modelId:self.selectedBtn.category.suggestionCategoryId modelName:self.selectedBtn.category.name successHandle:^(AFHTTPRequestOperation *operation, id responseObject) {
        [MBProgressHUD hideHUDForView:self.view];
        
        if (responseObject) {
            
            if ([[responseObject objectForKey:@"success"] boolValue]) {
                
                [MBProgressHUD showSuccess:@"反馈成功，谢谢你的宝贵意见!"];
                [self.navigationController popViewControllerAnimated:YES];
                
            } else {
                [MBProgressHUD showError:[responseObject objectForKey:@"message"]];
            }
            
        } else {
            [MBProgressHUD showError:@"未知错误"];
        }
        
    } failureHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
        [MBProgressHUD hideHUDForView:self.view];
         [MBProgressHUD showError:@"网络异常"];
    }];
}

- (BOOL)checkIsValidSuggestion
{
    if (self.sugView.text.length > 5) {
        if (self.sugView.text.length > 500) {
            [MBProgressHUD showError:@"文字个数已达到最大值"];
            return NO;
        }
        return YES;
    } else {
        
        [MBProgressHUD showError:@"内容必须大于5个字"];
        return NO;
    }
}

@end
